package com.ybbase.framework.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;

/**
 * @author cg
 * @desc: 令牌操作工具类
 * @date 2018/6/29 17:09
 */
public class JwtTokenUtil {


    private static final String SECRET = "%e7%8e%8b%e6%80%9d%e6%b6%b5"; //Token秘钥¬
    private static final int CALENDAR_FIELD = Calendar.HOUR;// Token过期时间
    private static final int CALENDAR_INTERVAL = 1;
    private static final String ISSUE = "system-service";// Token签发方

    /**
     * @Description: 签发Token
     * @author cg
     * @date 2018/6/29 17:08
     */
    // TODO 签发token时需要传入权限
    public static String createToken(String value, String... audience) {

        // 不予签发Token
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        // 签发时间
        Date issuedAt = new Date();
        // 过期时间
        Calendar expiresAtTime = Calendar.getInstance();
        expiresAtTime.add(CALENDAR_FIELD, CALENDAR_INTERVAL);
        Date expiresAt = expiresAtTime.getTime();

        // 生成Token
        return JWT.create()
                .withIssuer(ISSUE)
                .withAudience(audience)
                .withSubject(value)
                .withIssuedAt(issuedAt)
                .withExpiresAt(expiresAt)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * @Description: 解密Token获取Decoded
     * @author cg
     * @date 2018/6/29 17:24
     */
    private static DecodedJWT getDecoded(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        try {
            return verifier.verify(token);
        } catch (JWTVerificationException error) {
            return null;
        }
    }

    /**
     * @Description: 获取用户编码
     * @author cg
     * @date 2018/6/29 17:14
     */
    public static Integer getUserId(String token) {
        DecodedJWT decodedJWT = getDecoded(token);
        Integer cgint = 0;
        if (!StringUtils.isEmpty(decodedJWT)) {
            cgint = Integer.parseInt(decodedJWT.getClaim("sub").asString());
        }
        return cgint;
    }
}
